//
//  WrapperViewController.m
//  SXH
//
//  Created by 房 国生 on 15/7/14.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "WrapperViewController.h"

#import "SpotViewController.h"
#import "WebViewController.h"
#import "EScrollerView.h"
#import "CommonService.h"
#import "MapBaiduViewController.h"
#import "SpotDetailViewController.h"
#import "AroundViewController.h"

#import "HomeAdvertEntity.h"
#import "ParkEntity.h"

#import "FindViewController.h"
#import "MoreViewController.h"
#import "MeViewController.h"
#import "LocalProductViewController.h"
#import "IntroduceViewController.h"
#import "TicketProductViewController.h"
#import "MapImageViewController.h"
#import "NativeProductTableViewController.h"
#import "AroundTableViewController.h"
#import "ScanBarCodeViewController.h"
#import "UIView+AutoLayout.h"
#import "DownLoadOperation.h"
#import "MRProgressOverlayView.h"
#import "DBManager.h"
#import "ZipArchive.h"
#import "AppDelegate.h"
#import "JT3DScrollView.h"
#import "UIButton+WebCache.h"
#import "DXAlertView.h"
#import "Masonry.h"
#import "OpenUDID.h"
#import "XGPush.h"

#import "TCBlobDownloadManager.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "UIImageView+LK.h"
#import "activityTableViewCell.h"
#import "ActivityTableViewController.h"
#import "ComplainViewController.h"
#import "NewsView.h"
#import "PlantViewController.h"
#import "KRVideoPlayerController.h"
#import "ActivityListViewController.h"
#import "SDWebImageManager.h"
#import "Reachability.h"
#import "ShareChooseViewController.h"
#import "LoginViewController.h"

@interface WrapperViewController ()<EScrollerViewDelegate, ScanBarCodeDelegate, CommonServerDelegate, UIScrollViewDelegate>{
    NSArray *rssArray;
    EScrollerView *parkRowsScroller;
    int countInt;
    NSString *notice_index;
    long toTableViewHeight;
    NSMutableArray *activity_rowsTEMP;
    NSTimer *newsTimer;
    
    int enterGuidVC;
}

@property (nonatomic, strong) DownLoadOperation* operation;
@property (nonatomic, strong) UIButton *btnScan;
@property (nonatomic, strong) IBOutlet UIScrollView *scrollViewMain;
@property (nonatomic, strong) IBOutlet UIButton *btnDownload;
@property (nonatomic, strong) IBOutlet UILabel *labelProgress;

@property (weak, nonatomic) IBOutlet JT3DScrollView *scrollViewActvity;
@property (nonatomic, strong) NSMutableArray *mutableArrayActivity;
@property (nonatomic, strong) NSMutableArray *arrayAD;
@property (nonatomic, strong) NSMutableArray *park_rows;
@property (nonatomic , unsafe_unretained) TCBlobDownloadManager *sharedDownloadManager;
@property (assign) BOOL downloading;
@property (nonatomic, strong) IBOutlet UIProgressView *progressView;

@property (nonatomic, strong) IBOutlet UITableView *activityTableView;
@property (weak, nonatomic) IBOutlet UIButton *activityImage;
@property (assign, nonatomic) IBOutlet UIView *moreView;
@property (assign, nonatomic) IBOutlet UIView *moreViewDetail;
@property (assign, nonatomic) IBOutlet UIView *parkRowsView;
@property (strong, nonatomic) IBOutlet UIView *ScrollSubView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pic_height;//顶部图片高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *row_height;//景区活动高度
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *activityimage_height;//活动图片高度
@property (weak, nonatomic) IBOutlet UIView *kepuView;
@property (weak, nonatomic) IBOutlet UIView *happyView;
@property (weak, nonatomic) IBOutlet UIView *photographView;
@property (weak, nonatomic) IBOutlet UIButton *happyButtonView;
@property (weak, nonatomic) IBOutlet UILabel *happyLabelView;
@property (weak, nonatomic) IBOutlet UIButton *happyButtonView2;
@property (weak, nonatomic) IBOutlet UILabel *happyLabelView2;
@property (weak, nonatomic) IBOutlet UIButton *kepuButtonView;
@property (weak, nonatomic) IBOutlet UILabel *kepuLabelView;

//add by cy 2015.11.3
@property (strong, nonatomic) NewsView *newsView;

@property (nonatomic, strong) KRVideoPlayerController *videoController;
@end

#define K_cellIdentifier   @"activityTableViewCell"

@implementation WrapperViewController
@synthesize btnScan, scrollViewMain, parkEntity, arrayAD;
@synthesize btnDownload, scrollViewActvity;
@synthesize arrayBusiness, arrayToilet, arraySpot, arrayRoadLine, mutableArrayActivity,arrayBusinessTogether,arrayParkCar,arrayRest,arrayEnter,arrayHospital,arrayTogether,activityArr,topBannerArr;
@synthesize activityTableView;
@synthesize activityImage;
@synthesize moreView,moreViewDetail,newsView,parkRowsView;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    arraySpot = [[NSMutableArray alloc] init];
    arrayBusiness = [[NSMutableArray alloc] init];
    arrayToilet = [[NSMutableArray alloc] init];
    arrayRoadLine = [[NSMutableArray alloc] init];
    arrayEnter = [[NSMutableArray alloc] init];
    arrayHospital= [[NSMutableArray alloc] init];
    arrayRest = [[NSMutableArray alloc] init];
    arrayBusinessTogether=[[NSMutableArray alloc] init];
    arrayParkCar = [[NSMutableArray alloc] init];
    arrayTogether = [[NSMutableArray alloc] init];
    topBannerArr = [[NSMutableArray alloc]init];
    activity_rowsTEMP = [[NSMutableArray alloc]init];
//    if (iPhone4s) {
//        scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, 874);
//    }else{
//        scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, 780);
//    }
//    if (SCREEN_WIDTH >= 375) {
//        scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, 900);
//    }
    countInt = 0;
    toTableViewHeight = 0;
    
    self.ScrollSubView.frame = [UIScreen mainScreen].bounds;
//    self.ScrollSubView.hidden = YES;
    [self.scrollViewMain addSubview:self.ScrollSubView];
    //add by cy 2015.11.3
    // Do any additional setup after loading the view from its nib.
    self.labelTitle.text = parkEntity.title;
    self.scrollViewActvity.effect = JT3DScrollViewEffectNone;
    self.scrollViewActvity.delegate = self; // Use only for animate nextButton and previousButton
    self.scrollViewActvity.pagingEnabled = NO;
//    scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, self.ScrollSubView.bounds.size.height);
    arrayAD = [[NSMutableArray alloc] init];
    _progressView.hidden = YES;
    _labelProgress.hidden = YES;
    _downloading = NO;
    self.sharedDownloadManager = [TCBlobDownloadManager sharedDownloadManager];
    //[self initNavigateionBar];
    [self initAdController];
    mutableArrayActivity = [[NSMutableArray alloc] init];
    
    
    [btnDownload.layer setMasksToBounds:YES];
    [btnDownload.layer setCornerRadius:5.0]; //设置矩形四个圆角半径
    [btnDownload.layer setBorderWidth:1.0]; //边框宽度
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0.55, 0.77, 0.2, 1 });
    [btnDownload.layer setBorderColor:colorref];//边框颜色
    
    _labelProgress.hidden = YES;
    
    ParkEntity *entity = [DBManager selectParkByParkId:parkEntity.ID];
    if (entity != nil) {
        CommonService *service = [[CommonService alloc] init];
        if ([service getSpotDataFromLocal:entity.ID
                                   CityId:parkEntity.city_id
                                ArraySpot:arraySpot
                            ArrayBusiness:arrayBusiness
                              ArrayToilet:arrayToilet
                            ArrayRoadLine:arrayRoadLine
                               ParkEntity:parkEntity
                    ArrayBusinessTogether:arrayBusinessTogether
                                    Array:arrayTogether
                             TopBannerArr:nil
                              ActivityArr:nil] == YES) {
            [btnDownload setTitle:@"离线数据加载完成" forState:UIControlStateNormal];
            btnDownload.enabled = NO;
            
            [AppDelegate instance].file_from_local = YES;
        }
    }
    else {
        [AppDelegate instance].file_from_local = NO;
        [self getSpotFromInternetData];
    }
    
    [self getParkData];
    
    
    UITapGestureRecognizer *click = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(disappear)];
    UITapGestureRecognizer *click2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(disappear)];
    [moreView addGestureRecognizer:click];
    moreView.frame = CGRectMake(0, SCREEN_HEIGHT, self.view.bounds.size.width, self.view.bounds.size.height);
    [self.view addSubview:moreView];
    [moreViewDetail addGestureRecognizer:click2];
    moreViewDetail.frame = CGRectMake(0, -200, self.view.bounds.size.width, 200);
    [self.view addSubview:moreViewDetail];
    newsView=[[NewsView alloc] initWithFrame:CGRectMake(101.0f,  148/320.f*SCREEN_WIDTH + 4 , 211.0f, 21.0f)];
    [self.scrollViewMain addSubview:newsView];
    self.scrollViewMain.showsVerticalScrollIndicator = NO;
    
    enterGuidVC = 0;
    [self getActivityData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (IBAction)doMapAction:(id)sender {
    
    if (_downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
        return;
    }
    else {
        enterGuidVC = 0;
        if ([self loadSpotData] == YES) {
            [self enterMapSpot];
        }
    }
}

- (IBAction)doIntroduceAction:(id)sender {
    IntroduceViewController *vc = [[IntroduceViewController alloc] init];
    vc.parkId = [NSString stringWithFormat:@"%@",parkEntity.ID];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doGuideAction:(id)sender {
    
    if (_downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
        return;
    }
    else {
        if ([self loadSpotData] == YES) {
            SpotEntity *entity = [arraySpot objectAtIndex:0];
            SpotDetailViewController *vc = [[SpotDetailViewController alloc] init];
            vc.entity = entity;
            vc.parkEntity = parkEntity;
            vc.musicArrayNumber = 0;
            vc.musicArray = arraySpot;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (IBAction)doSpotAction:(id)sender {
    if (_downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
        return;
    }
    else {
        enterGuidVC = 1;
        if ([self loadSpotData] == YES) {
            [self enterSpotList];
        }
    }
}

- (IBAction)doTongyouAction:(id)sender
{
    UserEntity *userEntity = [UserEntity sharedInstance];
    if (userEntity.login == NO) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
        return;
    }
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
        ALERT_ERR_MSG(@"使用此项功能，需打开地图定位服务");
        return;
    }
    ShareChooseViewController *vc =[[ShareChooseViewController alloc] init];
    BMKUserLocation *autoLocation = [[BMKUserLocation alloc]init];
    LocationManagement *lm = [LocationManagement sharedInstance];

    vc.currentLatutide =lm.location.coordinate.latitude;
    vc.currentLontitude = lm.location.coordinate.longitude;
    vc.userId = userEntity.userId;
    //    vc.userId = @"1";
    vc.userLocation = autoLocation.location;
    [self.navigationController pushViewController:vc animated:YES];
    [lm stopGPS];
}


- (IBAction)doTicketAction:(id)sender {
    //扬州跳转门票列表其他城市跳转同程WEB
    if([parkEntity.ID isEqualToString:@"1"]||[parkEntity.ID isEqualToString:@"2085"]){
        TicketProductViewController *vc = [[TicketProductViewController alloc] init];
        vc.city_id = parkEntity.city_id;
        vc.park_id = parkEntity.ID;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        WebViewController *vc = [[WebViewController alloc] init];
        vc.url = parkEntity.ticket_url;
        vc.vcTitle = @"门票";
        vc.shareBtn.hidden= YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (IBAction)doAroundAction:(id)sender {
    AroundViewController *vc = [[AroundViewController alloc]init];
    vc.parkEntity = parkEntity;
    vc.category = 1;
    //AroundTableViewController *vc = [[AroundTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doFoodAction:(id)sender {
    AroundViewController *vc = [[AroundViewController alloc]init];
    vc.parkEntity = parkEntity;
    vc.category = 2;
    //AroundTableViewController *vc = [[AroundTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doHappyAction:(id)sender {
    AroundViewController *vc = [[AroundViewController alloc]init];
    vc.parkEntity = parkEntity;
    vc.category = 3;
    //AroundTableViewController *vc = [[AroundTableViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doLPAction:(id)sender {
    LocalProductViewController *vc = [[LocalProductViewController alloc] init];
     vc.cityid = parkEntity.city_id;
     vc.parkid = parkEntity.ID;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doGetMoreAction:(id)sender {
    moreView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    moreViewDetail.frame = CGRectMake(0,200, self.view.bounds.size.width, 200);
    [UIView commitAnimations];
    moreView.hidden=NO;
}

- (IBAction)doWeixinAction:(id)sender {
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = [NSString stringWithFormat:@"%@%@", IMAGE_URL, parkEntity.questionnaire_url];
    vc.vcTitle = @"问卷调查";
    vc.shareBtn.hidden = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)scanAction:(id)sender {
    ScanBarCodeViewController * vc = [[ScanBarCodeViewController alloc]init];
    vc.delegate = self;
    [self presentViewController:vc animated:YES completion:^{
    }];
}

- (void) initNavigateionBar {
    
    btnScan =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    [btnScan setBackgroundImage:[UIImage imageNamed:@"离线下载-白@2x"] forState:UIControlStateNormal];
    [btnScan addTarget:self action:@selector(scanAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *nextButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnScan];
    self.navigationItem.rightBarButtonItem = nextButtonItem;
}

/**
 *  没有网络时加载方法
 */
- (void)noNetworkLoad {
    EScrollerView *scroller = nil;
    scroller = [[EScrollerView alloc]initWithFrameRect1:CGRectMake(0, 0, SCREEN_WIDTH, 148/320.f*SCREEN_WIDTH) topBannerEntityArr:topBannerArr];
    self.pic_height.constant = 148/320.f*SCREEN_WIDTH +5;
    scroller.delegate =self;
    [self.scrollViewMain addSubview:scroller];
}


/**
 *  设置view属性
 */
- (void)setSubview {
    //设置显示科普或者娱乐
    if([parkEntity.park_class isEqualToString:@"1"]){
        _kepuView.hidden=NO;
        _happyView.hidden=YES;
        _happyButtonView.hidden=NO;
        _happyLabelView.hidden=NO;
    }
    else {
        _kepuView.hidden=YES;
        _happyView.hidden=NO;
        _happyButtonView.hidden=YES;
        _happyLabelView.hidden=YES;
        //                          _kepuButtonView.hidden=NO;
        //                          _kepuLabelView.hidden=NO;
    }
    
    //东关街的显示摄影 Icon
    if([parkEntity.title isEqualToString:@"东关街"]){
        _kepuButtonView.hidden=NO;
        _kepuLabelView.hidden=NO;
        _photographView.hidden=NO;
        _happyView.hidden=YES;
        _happyButtonView2.hidden=NO;
        _happyLabelView2.hidden=NO;
    }
    
    
    //设置 labelTitle
    self.labelTitle.text = parkEntity.title;
    
    //设置消息通知
    if([parkEntity.notice_rows count]>0){
        rssArray = parkEntity.notice_rows;
        notice_index=[[rssArray objectAtIndex:0] objectForKey:@"id"];
        [newsView.titleLabel setText:[[rssArray objectAtIndex:countInt] objectForKey:@"title"]];
        [newsView.descriptionLabel setText:@"TESTDESCRIPTION"];
        [newsView.newsButton addTarget:self action:@selector(topNewsInfoClicked:) forControlEvents:UIControlEventTouchUpInside];
        [UIView animateWithDuration:0.7 delay:0 options:0 animations:^(){
            newsView.alpha = 0.2;
            [newsView exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
            newsView.alpha = 1;
        } completion:^(BOOL finished){
            newsTimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(displayNews) userInfo:nil repeats:YES];
        }];
        
    }
    
//    if(parkEntity.activity_rows && [parkEntity.activity_rows count] > 0){
//        //设置单张广告图
//        NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, [[parkEntity.activity_rows objectAtIndex:0] objectForKey:@"album"]];
//        self.activityimage_height.constant = 100.f / 320.f * SCREEN_WIDTH;
//        [self.activityImage sd_setBackgroundImageWithURL:[NSURL URLWithString:imageUrl] forState:UIControlStateNormal];
//        activity_rowsTEMP = [NSMutableArray arrayWithArray:parkEntity.activity_rows];
//       [activity_rowsTEMP removeObjectAtIndex:0];
//   }
    
    //计算离 tableView 的距离
    if([activity_rowsTEMP count]<3)
        toTableViewHeight=(3-[activity_rowsTEMP count])*81;
    self.row_height.constant = (([activity_rowsTEMP count]>3)?3:[activity_rowsTEMP count]) *81;
    //刷新列表视图
    [activityTableView reloadData];
    
    scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, self.pic_height.constant+self.row_height.constant+self.activityimage_height.constant+250);
    if([parkEntity.park_rows count]>0){
        //设置周边景区、最下方的轮播图
        NSArray *array = parkEntity.park_rows;
        
        _park_rows=[[NSMutableArray alloc]init];
        if ([array count] == 0) {
        }
        else {
            for (NSDictionary* attributes in array) {
                HomeAdvertEntity *entity = [[HomeAdvertEntity alloc] init];
                entity = [entity initWithAttributesAttraction:attributes];
                [_park_rows addObject:entity];
            }
            parkRowsScroller = [[EScrollerView alloc] initWithFrameRect2:CGRectMake(0, parkRowsView.frame.origin.y+10, SCREEN_WIDTH, 41/320.f*SCREEN_WIDTH) ImageArray:_park_rows TitleArray:nil];
            scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, scrollViewMain.contentSize.height+parkRowsScroller.frame.size.height);
            
            //动态设置contentsize
        }
        
        parkRowsScroller.delegate =self;
        [self.ScrollSubView addSubview:parkRowsScroller];
        [parkRowsScroller mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(parkRowsView.mas_bottom);
            make.width.equalTo(@(SCREEN_WIDTH));
            make.left.equalTo(@0);
            make.height.equalTo(@(41/320.f*SCREEN_WIDTH));
        }];

        
    }
    self.ScrollSubView.frame = CGRectMake(0, 0, SCREEN_WIDTH, scrollViewMain.contentSize.height);
}

- (void) initAdController {
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
//                           [[AppDelegate instance].dicCurrentCity valueForKeyPath:@"id"], @"cityid",
                           parkEntity.ID, @"parkid",
                           @"advert_top", @"keyword", nil];
    
    /**
     *  如果没有网络连接,则从本地获取
     */
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) {
        NSFileManager *manage = [NSFileManager defaultManager];
        NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
        NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
        NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
        NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
        NSString *fileName = [NSString stringWithFormat:@"park-%@.zip",parkEntity.ID ];
        NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
        /**
         *  如果本地没有文件夹 直接返回
         */
        if (![manage fileExistsAtPath:folder]) {
            [self noNetworkLoad];
            return;
        }
        if (![manage fileExistsAtPath:filePath]) {
            [self noNetworkLoad];
            return;
        }
        /**
         *  如果本地有文件
         */
        [service getSpotDataFromLocal:parkEntity.ID CityId:parkEntity.city_id ArraySpot:arraySpot ArrayBusiness:arrayBusiness ArrayToilet:arrayToilet ArrayRoadLine:arrayRoadLine ParkEntity:parkEntity ArrayBusinessTogether:arrayBusinessTogether Array:arrayTogether TopBannerArr:topBannerArr ActivityArr:activityArr];
        [self noNetworkLoad];
        return;
        
    }
    [service getNetWorkData:param
                       Path:ADPATH
                  Successed:^(id entity) {
                      NSDictionary *row = (NSDictionary *)entity;
                      
                      NSMutableArray *array = [row objectForKey:@"rows"];
                      EScrollerView *scroller = nil;
                      for (NSDictionary* attributes in array) {
                          HomeAdvertEntity *entity = [[HomeAdvertEntity alloc] init];
                          entity = [entity initWithAttributes:attributes];
                          [arrayAD addObject:entity];
                      }
                      
                      if ([array count] == 0) {
                          //                          NSMutableArray *array2 = [[NSMutableArray alloc] init];
                          //                          [array2 addObject:arrayAD];
                          //                          scroller = [[EScrollerView alloc] initWithFrameRect:CGRectMake(0, 0, 320, 140)
                          //                                                                   ImageArray:array2
                          //                                                                   TitleArray:nil];
                      }
                      else {
                          scroller = [[EScrollerView alloc] initWithFrameRect:CGRectMake(0, 0, SCREEN_WIDTH, 148/320.f*SCREEN_WIDTH)
                                                                   ImageArray:arrayAD
                                                                   TitleArray:nil];
                          self.pic_height.constant = 148/320.f*SCREEN_WIDTH +5+30;
                      }
                      
                      scroller.delegate =self;
                      [self.scrollViewMain addSubview:scroller];
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      DebugLog(@"%@", message);
                  }];
}

- (void) getParkData {
    [super showLoadingView:YES];
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           parkEntity.ID, @"id",
                           @"8ae86cfacd9744b68aecd3a6caa5f78f", @"appid",nil];
    
    /**
     *  如果没有网络连接,则从本地获取
     */
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) {
        NSFileManager *manage = [NSFileManager defaultManager];
        NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
        NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
        NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
        NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
        NSString *fileName = [NSString stringWithFormat:@"park-%@.zip",parkEntity.ID ];
        NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
        /**
         *  如果本地没有文件夹 直接返回
         */
        if (![manage fileExistsAtPath:folder]) {
//            [self setSubview];
            [super showLoadingView:NO];
            return;
        }
        if (![manage fileExistsAtPath:filePath]) {
//            [self setSubview];
            [super showLoadingView:NO];
            return;
        }
        /**
         *  如果本地有文件
         */
        [service getSpotDataFromLocal:parkEntity.ID CityId:parkEntity.city_id ArraySpot:arraySpot ArrayBusiness:arrayBusiness ArrayToilet:arrayToilet ArrayRoadLine:arrayRoadLine ParkEntity:parkEntity ArrayBusinessTogether:arrayBusinessTogether Array:arrayTogether TopBannerArr:topBannerArr ActivityArr:activity_rowsTEMP];
        [super showLoadingView:NO];
//        [self setSubview];
        return;
        
    }
    
    
    [service getNetWorkData:param
                       Path:PARK_ENTITY_PATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      
                      NSDictionary *dic_row = [dic objectForKey:@"row"];
                      
                      parkEntity = [[ParkEntity alloc] init];
                      parkEntity = [parkEntity initWithAttributes:dic_row];
                      [self setSubview];
                      [super showLoadingView:NO];
                      
                      
                      //东关街的显示摄影 Icon
                      if([parkEntity.title isEqualToString:@"东关街"]){
                          _kepuButtonView.hidden=NO;
                          _kepuLabelView.hidden=NO;
                          _photographView.hidden=NO;
                          _happyView.hidden=YES;
                          _happyButtonView2.hidden=NO;
                          _happyLabelView2.hidden=NO;
                      }
                      
                      
                      //设置 labelTitle
                      self.labelTitle.text = parkEntity.title;
                      
                      //设置消息通知
                      if([parkEntity.notice_rows count]>0){
                          rssArray=parkEntity.notice_rows;
                          notice_index=[[rssArray objectAtIndex:0] objectForKey:@"id"];
                          [newsView.titleLabel setText:[[rssArray objectAtIndex:countInt] objectForKey:@"title"]];
                          [newsView.descriptionLabel setText:@"TESTDESCRIPTION"];
                          [newsView.newsButton addTarget:self action:@selector(topNewsInfoClicked:) forControlEvents:UIControlEventTouchUpInside];
                          [UIView animateWithDuration:0.7 delay:0 options:0 animations:^(){
                              newsView.alpha = 0.2;
                              [newsView exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
                              newsView.alpha = 1;
                          } completion:^(BOOL finished){
                                newsTimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(displayNews) userInfo:nil repeats:YES];
                          }];
                      }

                      if(parkEntity.activity_rows && [parkEntity.activity_rows count] > 0){
                          //设置单张广告图
                          NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, [[parkEntity.activity_rows objectAtIndex:0] objectForKey:@"album"]];
//                          self.activityimage_height.constant = 100.f / 320.f * SCREEN_WIDTH;
                          [self.activityImage sd_setBackgroundImageWithURL:[NSURL URLWithString:imageUrl] forState:UIControlStateNormal];
                          activity_rowsTEMP = [NSMutableArray arrayWithArray:parkEntity.activity_rows];
//                          [activity_rowsTEMP removeObjectAtIndex:0];
                      }
                      
                      //计算离 tableView 的距离
                      if([activity_rowsTEMP count]<3)
                          toTableViewHeight=(3-[activity_rowsTEMP count])*81;
                      self.row_height.constant = (([activity_rowsTEMP count]>3)?3:[activity_rowsTEMP count]) *81;
                      self.actityHeight.constant = (([activity_rowsTEMP count]>3)?3:[activity_rowsTEMP count]) *81;
                      //刷新列表视图
                      [activityTableView reloadData];
                      
                      scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, self.pic_height.constant+self.row_height.constant+self.activityimage_height.constant+230);
                      if([parkEntity.park_rows count]>0){
                          //设置周边景区、最下方的轮播图
                          NSArray *array = parkEntity.park_rows;
                          
                          _park_rows=[[NSMutableArray alloc]init];
                          if ([array count] == 0)
                          {
                          } else {
                              for (NSDictionary* attributes in array) {
                                  HomeAdvertEntity *entity = [[HomeAdvertEntity alloc] init];
                                  entity = [entity initWithAttributesAttraction:attributes];
                                  [_park_rows addObject:entity];
                              }
                                  parkRowsScroller = [[EScrollerView alloc] initWithFrameRect2:CGRectMake(0, parkRowsView.frame.origin.y+10, SCREEN_WIDTH, 41/320.f*SCREEN_WIDTH) ImageArray:_park_rows TitleArray:nil];
                        scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, scrollViewMain.contentSize.height+parkRowsScroller.frame.size.height);
                              
                              //动态设置contentsize
                          }
                          
                          parkRowsScroller.delegate =self;
                          [self.ScrollSubView addSubview:parkRowsScroller];
                          [parkRowsScroller mas_makeConstraints:^(MASConstraintMaker *make) {
                              make.top.equalTo(parkRowsView.mas_bottom);
                              make.width.equalTo(@(SCREEN_WIDTH));
                              make.left.equalTo(@0);
                              make.height.equalTo(@(41/320.f*SCREEN_WIDTH));
                          }];
//
//                          [self.view addConstraint:[NSLayoutConstraint constraintWithItem:parkRowsScroller
//                                                                                attribute:NSLayoutAttributeTop
//                                                                                relatedBy:NSLayoutRelationEqual
//                                                                                   toItem:parkRowsView
//                                                                                attribute:NSLayoutAttributeBottom
//                                                                               multiplier:1.0f
//                                                                                 constant:0]];
//                          
//                          [self.view addConstraint:[NSLayoutConstraint
//                                                    constraintWithItem:parkRowsScroller
//                                                    attribute:NSLayoutAttributeCenterX
//                                                    relatedBy:NSLayoutRelationEqual
//                                                    toItem:self.view
//                                                    attribute:NSLayoutAttributeCenterX
//                                                    multiplier:1
//                                                    constant:0]];
//                          
//                          [self.view addConstraint:[NSLayoutConstraint
//                                                    constraintWithItem:parkRowsScroller
//                                                    attribute:NSLayoutAttributeHeight
//                                                    relatedBy:NSLayoutRelationEqual
//                                                    toItem:nil
//                                                    attribute:NSLayoutAttributeNotAnAttribute
//                                                    multiplier:1
//                                                    constant:41/320.f*SCREEN_WIDTH]];
//                          
//                          [self.view addConstraint:[NSLayoutConstraint
//                                                    constraintWithItem:parkRowsScroller
//                                                    attribute:NSLayoutAttributeWidth
//                                                    relatedBy:NSLayoutRelationEqual
//                                                    toItem:nil
//                                                    attribute:NSLayoutAttributeNotAnAttribute
//                                                    multiplier:1
//                                                    constant:SCREEN_WIDTH]];
                          
                      }
                      else
                      {
                          self.parkRowsView.hidden = YES;
                      }
                      self.ScrollSubView.frame = CGRectMake(0, 0, SCREEN_WIDTH, scrollViewMain.contentSize.height);
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      [super showLoadingView:NO];
                      DebugLog(@"%@", message);
                  }];
}

- (void) pushScanResultInfo:(NSString *)url {
    //扫描景点跳转景点介绍   
    NSRange range = [url rangeOfString:@"attraction_id"];
    if(range.length > 0){
        if (_downloading == YES) {
            ALERT_ERR_MSG(SourceDownloading);
            return;
        }
        else {
            if ([self loadSpotData] == YES) {
                SpotEntity *entity = [arraySpot objectAtIndex:0];
                NSString *aid = [url substringFromIndex:([url rangeOfString:@"attraction_id"].location+14)];
                int tag;
                
                for(tag=0;tag<[arraySpot count];tag++){
                    entity = [arraySpot objectAtIndex:tag];
                    if([entity.ID isEqualToString:aid] == YES)
                        break;
                    else
                        continue;
                }
                
                if (tag < [arraySpot count]) {
                    SpotDetailViewController *vc = [[SpotDetailViewController alloc] init];
                    vc.entity = entity;
                    vc.parkEntity = parkEntity;
                    vc.musicArrayNumber = tag;
                    vc.musicArray = arraySpot;
                    [self.navigationController pushViewController:vc animated:YES];
                }
                else {
                    NSString *msg = [NSString stringWithFormat:@"%@中未找到此景点", parkEntity.title];
                    ALERT_ERR_MSG(msg);
                }
            }
            else {
                ALERT_ERR_MSG(@"未加载到资源包");
            }
        }
    }
    else if ([url rangeOfString:@"plant"].location > 0) {
        //扫描植物跳转植物介绍
        WebViewController *vc =[[WebViewController alloc] init];
        vc.vcTitle = @"扫描";
        vc.url = [NSString stringWithFormat:@"%@%@",url,@"?app_open=1&ignore=1"];
        vc.shareBtn.hidden = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        WebViewController *vc =[[WebViewController alloc] init];
        vc.vcTitle = @"扫描";
        vc.url = url;
        vc.shareBtn.hidden =YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (CGFloat) getDownloadProgress:(CGFloat)progress {
    
    int i_progress =  progress*100;
    NSString *title = [NSString stringWithFormat:@"下载进度（%d）",i_progress];
    [btnDownload setTitle:title forState:UIControlStateNormal];
    
    return 0.0f;
}

- (void) finishDownload:(BOOL)success {
    DebugLog(@"donwnload finish status = %d", success);
}

- (void)performBlock:(void(^)())block afterDelay:(NSTimeInterval)delay {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), block);
}

- (void) saveDataToFile:(NSString *)url SavePath:(NSString *)aSavePath FileName:(NSString *)aFileName{
    
}

- (void) getSpotFromInternetData {
    
    //读取本地数据库是否有该文件
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           parkEntity.ID, @"parkid", nil];
    
    [service getNetWorkData:param
                       Path:SPOTPATH
                  Successed:^(id entity) {
                      NSDictionary *dic = (NSDictionary *)entity;
                      NSArray *array = [dic objectForKey:@"attractionRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [arraySpot addObject:entity2];
                      }
                      
                      array = [dic objectForKey:@"businessRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [[AppDelegate instance].arrayBusiness addObject:entity2];
                      }
                      
                      array = [dic objectForKey:@"toiletRows"];
                      
                      for (NSDictionary* attributes in array) {
                          SpotEntity *entity2 = [[SpotEntity alloc] init];
                          entity2 = [entity2 initWithAttributes:attributes];
                          [[AppDelegate instance].arrayToilet addObject:entity2];
                      }
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                  }];
}


- (void)createCard {
    CGFloat width = CGRectGetWidth(self.scrollViewActvity.frame)/4 - 5;
    CGFloat height = CGRectGetHeight(self.scrollViewActvity.frame);
    for (int i = 0; i < [mutableArrayActivity count]; i++) {
        NSDictionary *dicActivity = [mutableArrayActivity objectAtIndex:i];
        CGFloat x = self.scrollViewActvity.subviews.count * width + (self.scrollViewActvity.subviews.count + 1)*4;
        
        UIButton *btnActivity = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, width, height)];
        btnActivity.layer.cornerRadius = 8.;
        
        NSString *imagePath = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, [dicActivity valueForKeyPath:@"album_thumb"]];
        [btnActivity sd_setImageWithURL:[NSURL URLWithString:imagePath] forState:UIControlStateNormal];
        [btnActivity addTarget:self action:@selector(btnActivityClicked:) forControlEvents:UIControlEventTouchUpInside];
        btnActivity.tag = i;
        [self.scrollViewActvity addSubview:btnActivity];
        self.scrollViewActvity.contentSize = CGSizeMake(x + width, height);
    }
}

- (void) getActivityData {
    //读取本地数据库是否有该文件
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           parkEntity.ID, @"parkid",
                           @"1",@"page",
                           @"10", @"limit",nil];
    
    /**
     *  如果没有网络连接,则从本地获取
     */
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) {
        NSFileManager *manage = [NSFileManager defaultManager];
        NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
        NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
        NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
        NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
        NSString *fileName = [NSString stringWithFormat:@"park-%@.zip",parkEntity.ID ];
        NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
        /**
         *  如果本地没有文件夹 直接返回
         */
        if (![manage fileExistsAtPath:folder]) {
            [self setSubview];
            return;
        }
        if (![manage fileExistsAtPath:filePath]) {
            [self setSubview];
            return;
        }
        /**
         *  如果本地有文件
         */
        [service getSpotDataFromLocal:parkEntity.ID CityId:parkEntity.city_id ArraySpot:arraySpot ArrayBusiness:arrayBusiness ArrayToilet:arrayToilet ArrayRoadLine:arrayRoadLine ParkEntity:parkEntity ArrayBusinessTogether:arrayBusinessTogether Array:arrayTogether TopBannerArr:topBannerArr ActivityArr:activity_rowsTEMP];
        [super showLoadingView:NO];
        [self setSubview];
        return;
        
    }
    
    [service getNetWorkData:param
                       Path:PARK_ACTIVITY
                  Successed:^(id entity) {
                      NSLog(@"成功");
                      [self setSubview];
                      [super showLoadingView:NO];
                      
//                      NSDictionary *dic = (NSDictionary *)entity;
//                      NSArray *array = [dic objectForKey:@"rows"];
//                      
//                      for (NSDictionary* attributes in array) {
//                          [mutableArrayActivity addObject:attributes];
//                      }
//                      
//                      [self createCard];
                      
                  } Failed:^(NSInteger errorCode, NSString *message) {
                      NSLog(@"失败");
                  }];
}

- (void)btnActivityClicked:(id)sender {
    UIButton *btn = (UIButton *)sender;
    NSDictionary *dicActivity = [mutableArrayActivity objectAtIndex:btn.tag];
    
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = [dicActivity valueForKeyPath:@"html"];
    vc.vcTitle = [dicActivity valueForKeyPath:@"title"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (BOOL) loadSpotData {
    // 调整示例frame
    NSString *fileName = @"getSource";//[NSString stringWithFormat:@"park_%@.zip",parkEntity.ID ];
    //NSString *aSavePath = @"lyss";
    
    //检查本地文件是否已存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
    
    NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
    
    if (![fileManager fileExistsAtPath:folder]) {
        BOOL blCreateFolder= [fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:NULL];
        if (blCreateFolder) {
            blCreateFolder= [fileManager createDirectoryAtPath:park_path withIntermediateDirectories:NO attributes:nil error:NULL];
            if (blCreateFolder) {
                NSLog(@" folder success2");
            }else {
                NSLog(@" folder fial2");
            }
        }
        if (blCreateFolder) {
            NSLog(@" folder success");
        }else {
            NSLog(@" folder fial");
        }
    } else {
        NSLog(@" 沙盒文件已经存在");
    }
    
    if ([DBManager selectParkByParkId:parkEntity.ID] != nil) {// && [fileManager fileExistsAtPath:filePath]
        
        CommonService *service = [[CommonService alloc] init];
        
        if ([arraySpot count] == 0) {
            if ([service getSpotDataFromLocal:parkEntity.ID
                                       CityId:parkEntity.city_id
                                    ArraySpot:arraySpot
                                ArrayBusiness:arrayBusiness
                                  ArrayToilet:arrayToilet
                                ArrayRoadLine:arrayRoadLine
                                   ParkEntity:parkEntity
                                ArrayBusinessTogether:arrayBusinessTogether
                                        Array:arrayTogether TopBannerArr:topBannerArr ActivityArr:activityArr] == YES) {
                return YES;
            }
            else {
                ALERT_ERR_MSG(DownloadCacheSourceFail);
                return NO;
            }
        }
        else {
            return YES;
        }
    }
    
    else {
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"提示"
                                                    contentText:@"下载景区资料？"
                                                leftButtonTitle:@"取消"
                                               rightButtonTitle:@"确定"];
        [alert show];
        alert.leftBlock = ^() {
            NSLog(@"left button clicked");
        };
        alert.rightBlock = ^() {
            [self downloadPackage];
        };
        alert.dismissBlock = ^() {
            NSLog(@"Do something interesting after dismiss block");
        };
        return NO;
    }
}

- (void) downloadPackage {
    NSString *fileName = [NSString stringWithFormat:@"park-%@.zip",parkEntity.ID ];
    //NSString *aSavePath = @"lyss";
    
    //检查本地文件是否已存在
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
//    NSString *document = [NSString stringWithFormat:@"%@/Documents",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *fileNameTemp = [NSString stringWithFormat:@"park_%@",parkEntity.ID ];
    NSString *park_path = [folder stringByAppendingPathComponent:fileNameTemp];
    
    NSString *filePath = [park_path stringByAppendingPathComponent:fileName];
    
    if (![fileManager fileExistsAtPath:folder]) {
        BOOL blCreateFolder= [fileManager createDirectoryAtPath:folder withIntermediateDirectories:NO attributes:nil error:NULL];
        if (blCreateFolder) {
            blCreateFolder= [fileManager createDirectoryAtPath:park_path withIntermediateDirectories:NO attributes:nil error:NULL];
            if (blCreateFolder) {
                NSLog(@" folder success2");
            }else {
                NSLog(@" folder fial2");
            }
        } else {
            
        }
        if (blCreateFolder) {
            NSLog(@" folder success");
        }else {
            NSLog(@" folder fial");
        }
    } else {
        NSLog(@" 沙盒文件已经存在");
    }
    
    //NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/lysss"];
    if (![fileManager fileExistsAtPath:filePath]) {
        _progressView.hidden = NO;
        _downloading = YES;
        [_progressView setProgress:0];
        _labelProgress.hidden = NO;
        _labelProgress.text = [NSString stringWithFormat:@"(%.1f%%)", 0*100.0];
        //判断是否链接LET-FI设备，并试图读取SD卡上的相关内容
        NSString *LET_FI_URL = [NSString stringWithFormat:@"%@/resource/park-%@.zip", LET_FI, parkEntity.ID];
        [self downloadPackage:LET_FI_URL ParkPath:park_path];
        //        if ([CommonService isExistenceLETFINetwork:LET_FI_URL] == YES) {
        //
        //        } else {
        //            [self downloadPackage:url ParkPath:park_path];
        //        }
    }
    else {
        
        NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:filePath];
        NSData *data = [file readDataToEndOfFile];//得到xml文件
        
        NSString* aStr;
        aStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];         //转换为NSString
        NSLog( @"aStr is %@", aStr );
        
        /**
         *  如果文件存在则删除重新执行本方法
         */
        [fileManager removeItemAtPath:filePath error:nil];
        [self downloadPackage];
    }
}

- (void)cancelAll:(id)sender
{
    [self.sharedDownloadManager cancelAllDownloadsAndRemoveFiles:YES];
}

- (IBAction)doBack:(id)sender {
    [self.sharedDownloadManager cancelAllDownloadsAndRemoveFiles:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - BlobDownloadManager Delegate (Optional, your choice)


- (void)download:(TCBlobDownload *)blobDownload didReceiveFirstResponse:(NSURLResponse *)response {
}

- (void)download:(TCBlobDownload *)blobDownload
  didReceiveData:(uint64_t)receivedLength
         onTotal:(uint64_t)totalLength {
    
}

- (void)download:(TCBlobDownload *)blobDownload didStopWithError:(NSError *)error {
}

- (void)download:(TCBlobDownload *)blobDownload didCancelRemovingFile:(BOOL)fileRemoved {
    
}

- (void)downloadDidFinishWithDownload:(TCBlobDownload *)blobDownload {
    
}

- (BOOL) downloadPackage:(NSString *)url ParkPath:(NSString *)park_path {
    
    return [self.sharedDownloadManager startDownloadWithURL:[NSURL URLWithString:url]
                                                 customPath:park_path
                                              firstResponse:^(NSURLResponse *response) {
                                                  
                                              }
                                                   progress:^(float receivedLength, float totalLength) {
                                                       NSLog(@"totalBytesRead = %f totalBytesExpectedToRead = %f",receivedLength,totalLength);
                                                       _downloading = YES;
                                                       float progress = receivedLength / (float)totalLength;
                                                       [_progressView setProgress:progress];
                                                       _labelProgress.text = [NSString stringWithFormat:@"(%.1f%%)", progress*100.0];
                                                       _progressView.hidden = NO;
                                                       _labelProgress.hidden = NO;
                                                       parkEntity.package_size = [NSString stringWithFormat:@"%fM", totalLength/(1024.0*1024)];
                                                   }
                                                      error:^(NSError *error) {
                                                          
                                                          if ([url containsString:LET_FI] == YES) {
                                                              UserEntity *user = [UserEntity sharedInstance];
                                                              LocationManagement *lm = [LocationManagement sharedInstance];
                                                              NSString *longitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.longitude ];
                                                              NSString *latitude = [NSString stringWithFormat:@"%f", lm.location.coordinate.latitude ];
                                                              
                                                              NSString *url = [NSString stringWithFormat:@"%@%@?parkid=%@&userid=%@&longitude=%@&latitude=%@&phone_guid=%@&simple=%@",
                                                                               BASEURL, PARK_SOURCE, parkEntity.ID, user.userId, longitude, latitude, [OpenUDID value], @"1"];
                                                              [self downloadPackage:url ParkPath:park_path];
                                                              _progressView.hidden = NO;
                                                              _labelProgress.hidden = NO;
                                                              
                                                              
                                                          }
                                                          else {
                                                              _progressView.hidden = YES;
                                                              _labelProgress.hidden = YES;
                                                              _downloading = NO;
                                                              NSLog(@"error = %@",error);
                                                              ALERT_ERR_MSG(DownloadWebsiteSourceFail);
                                                          }
                                                      }
                                                   complete:^(BOOL downloadFinished, NSString *pathToFile) {
                                                       if (downloadFinished)
                                                       {
                                                           _progressView.hidden = YES;
                                                           _labelProgress.hidden = YES;
                                                           //定义一个布尔类型的对象
                                                           BOOL ifsucess;
                                                           //在objective－c种，正确是YES 错误是NO
                                                           ifsucess = NO;
                                                           //获取上面fileData对象中通过NSFileManager对象获取的文件中的内容，然后再创建一个新的路径，并存储
                                                           
                                                           NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:pathToFile];
                                                           NSData *data = [file readDataToEndOfFile];//得到xml文件
                                                           //对布尔型对象进行判断
                                                           if(data) {
                                                               NSLog(@"create file sucess");
                                                               //we need save this data to the sqlite
                                                               parkEntity.local_path = pathToFile;
                                                               
                                                               //解压压缩包
                                                               ZipArchive *za = [[ZipArchive alloc] init];
                                                               if ([za UnzipOpenFile: pathToFile]) {
                                                                   BOOL ret = [za UnzipFileTo:park_path overWrite: YES];
                                                                   if (NO == ret){
                                                                       NSLog(@"za UnzipFileTo fail");
                                                                       ALERT_ERR_MSG(@"解压失败");
                                                                   }
                                                                   else {
                                                                       //ALERT_ERR_MSG(@"解压成功");
                                                                       
                                                                       //删除压缩包文件
                                                                       [CommonService deleteFile:pathToFile];
                                                                       //获取文件夹的大小
                                                                       parkEntity.package_size = [CommonService getFolderSize:parkEntity.ID];
                                                                       
                                                                       [DBManager createTable];
                                                                       [DBManager saveOrUpdataParkEntity:parkEntity];
                                                                       
                                                                       CommonService *service = [[CommonService alloc] init];
                                                                       if ([service getSpotDataFromLocal:parkEntity.ID
                                                                                                  CityId:parkEntity.city_id
                                                                                               ArraySpot:arraySpot
                                                                                           ArrayBusiness:arrayBusiness
                                                                                             ArrayToilet:arrayToilet
                                                                                           ArrayRoadLine:arrayRoadLine
                                                                                              ParkEntity:parkEntity
                                                                                   ArrayBusinessTogether:arrayBusinessTogether
                                                                                                   Array:arrayTogether TopBannerArr:topBannerArr ActivityArr:activityArr] == YES) {
                                                                           if (enterGuidVC == 0) {
                                                                               [self enterMapSpot];
                                                                           }
                                                                           else {
                                                                               [self enterSpotList];
                                                                           }
                                                                       }
                                                                       else {
                                                                           ALERT_ERR_MSG(DownloadCacheSourceFail);
                                                                       }
                                                                   }
                                                                   [za UnzipCloseFile];
                                                               }
                                                               else {
                                                                   
                                                                   /**
                                                                    *  2016.7.16 朱伟修改下载bug
                                                                    *  当服务器没有资源包时 本地下载失败仍会生成0字节的zip文件 此处删掉
                                                                    */
                                                                   //{{
                                                                   NSLog(@"%@",parkEntity.ID);
                                                                   NSFileManager *fileManager = [NSFileManager defaultManager];
                                                                   NSString *tmpPath = [NSString stringWithFormat:@"%@park-%@.zip",[pathToFile substringToIndex:pathToFile.length - 9],parkEntity.ID];
                                                                   if ([fileManager fileExistsAtPath:tmpPath]) {
                                                                       [fileManager removeItemAtPath:tmpPath error:nil];
                                                                   }
                                                                   //}}
                                                               }
                                                           }
                                                           else {
                                                               if ([url containsString:LET_FI] != YES) {
                                                                   ALERT_ERR_MSG(DownloadFail);
                                                               }
                                                           }
                                                           _downloading = NO;
                                                           
                                                       }
}];
}


//



- (void)EScrollerViewDidClicked:(NSUInteger)index {
    DebugLog(@"index==%lu",(unsigned long)index);
    if (index == [arrayAD count]) {
        index = 0;
    }
    HomeAdvertEntity *entity = [arrayAD objectAtIndex:index];
    
    if (entity.url == nil || entity.url.length == 0) {
        
    }
    else {
        if ([entity.url rangeOfString:@"mp4"].location != NSNotFound){
            
            [self playVideoWithURL:[NSURL URLWithString:entity.url ] ];

        }
        else{
            WebViewController * vc = [[WebViewController alloc]init];
            vc.url = entity.url;
            vc.vcTitle = entity.title;
            vc.shareBtn.hidden = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (void)EScrollerViewDidClicked2:(NSUInteger)index {
    if (_downloading == YES) {
        ALERT_ERR_MSG(SourceDownloading);
        return;
    }
    else {
        if (index == [_park_rows count]) {
            index = 0;
        }
        HomeAdvertEntity *entity = [_park_rows objectAtIndex:index];
        
        if([entity.is_business isEqualToString:@"1"]){
            parkEntity.ID=entity.activityId;
            [parkRowsScroller removeFromSuperview];
            newsView=nil;
            [newsView removeFromSuperview];
            //取消定时器
            [newsTimer invalidate];
            newsTimer = nil;
            [self viewDidLoad];
        }
        else{
            IntroduceViewController *vc = [[IntroduceViewController alloc] init];
            vc.parkId = [NSString stringWithFormat:@"%@",entity.activityId];
            [self.navigationController pushViewController:vc animated:YES];
        }

    }
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [parkRowsView setFrame:CGRectMake(0.0f, 710.0f-toTableViewHeight, SCREEN_WIDTH, 21.0f)];
    
//      if (iPhone4s) {
//          scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, 874-toTableViewHeight);
//      }else{
//          scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, 780-toTableViewHeight);
//      }
//    if (SCREEN_WIDTH >= 375) {
//        scrollViewMain.contentSize = CGSizeMake(scrollViewMain.contentSize.width, 900-toTableViewHeight);
    }
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"WrapperViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"WrapperViewController"];
}


#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return ([activity_rowsTEMP count]>3)?3:[activity_rowsTEMP count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = K_cellIdentifier;
    activityTableViewCell *cell = (activityTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:K_cellIdentifier owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    cell.activityName.text = [[activity_rowsTEMP objectAtIndex:indexPath.row] objectForKey:@"title"];
    cell.activityIntroduce.text= [[activity_rowsTEMP objectAtIndex:indexPath.row] objectForKey:@"description"];
    NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", IMAGE_URL, [[activity_rowsTEMP objectAtIndex:indexPath.row] objectForKey:@"album_thumb"]];
    cell.activityImage.imageURL=[NSURL URLWithString:imageUrl];
    //    long count=([parkEntity.activity_rows count]>3)?2:([parkEntity.activity_rows count]-1);
    if(indexPath.row==2){
        cell.borderLine.hidden=YES;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 81;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //当手指离开某行时，就让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = [[activity_rowsTEMP objectAtIndex:indexPath.row] valueForKeyPath:@"html"];
    vc.vcTitle = [[activity_rowsTEMP objectAtIndex:indexPath.row] valueForKeyPath:@"title"];
    vc.contentShare = [[activity_rowsTEMP objectAtIndex:indexPath.row] valueForKeyPath:@"description"];
    [[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", IMAGE_URL, [[activity_rowsTEMP objectAtIndex:indexPath.row] objectForKey:@"album_thumb"]]] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        vc.imageShare = image;}];

    [self.navigationController pushViewController:vc animated:YES];
}

-(void)disappear {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    moreViewDetail.frame = CGRectMake(0, -200, self.view.bounds.size.width, 200);
    [UIView commitAnimations];
    moreView.frame = CGRectMake(0, SCREEN_HEIGHT, self.view.bounds.size.width, self.view.bounds.size.height);
    moreView.hidden =YES;
}

-(IBAction)gotoRecomment:(id)sender {
    NSDictionary *dic=[parkEntity.activity_rows objectAtIndex:0];
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = [dic valueForKey:@"html"];
    vc.vcTitle = [dic valueForKey:@"title"];
    vc.contentShare = [dic valueForKey:@"description"];
    [[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", IMAGE_URL, [dic objectForKey:@"album_thumb"]]] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        vc.imageShare = image;}];
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)gotoMoreActivity:(id)sender {
    ActivityTableViewController *vc = [[ActivityTableViewController alloc] init];
    vc.parkEntity=parkEntity;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)doTechnologyAction:(id)sender {
    PlantViewController * vc = [[PlantViewController alloc] init];
    if (parkEntity.animal_knowledge) {
        if ([parkEntity.animal_knowledge isEqualToString:@"1"]) {
    vc.animal_knowledge = parkEntity.animal_knowledge;
        }
    }

    vc.parkId = parkEntity.ID;
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)gotoComplain:(id)sender{
    ComplainViewController *vc = [[ComplainViewController alloc] init];
    vc.parkEntity=parkEntity;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)playVideoWithURL:(NSURL *)url
{
    if (!self.videoController) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        self.videoController = [[KRVideoPlayerController alloc] initWithFrame:CGRectMake(0, 0, width, width*(9.0/16.0))];
        __weak typeof(self)weakSelf = self;
        [self.videoController setDimissCompleteBlock:^{
            weakSelf.videoController = nil;
        }];
        [self.videoController showInWindow];
    }
    self.videoController.contentURL = url;
}

-(void)displayNews {
    countInt++;
//    long num = [rssArray count] >= 3 ? 3:[rssArray count];
    if (countInt >= [rssArray count])
        countInt=0;
    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = 0.5f ;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.removedOnCompletion = YES;
    animation.type = @"cube";
    
    notice_index=[[rssArray objectAtIndex:countInt] objectForKey:@"id"];
    
    [newsView.layer addAnimation:animation forKey:@"animationID"];
    [newsView setViewWithTitle:[[rssArray objectAtIndex:countInt] objectForKey:@"title"] description:@"test"];
}

- (void)topNewsInfoClicked:(id)sender {
    WebViewController *vc = [[WebViewController alloc] init];
    vc.url = [NSString stringWithFormat:@"%@%@",PARKNOTICE_URL,notice_index];
    vc.vcTitle = [[rssArray objectAtIndex:countInt] objectForKey:@"title"];
    vc.shareBtn.hidden = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)pushToActivityList:(id)sender {
    ActivityListViewController *mvc = [[ActivityListViewController alloc]init];
    mvc.parkid = parkEntity.ID;
    [self.navigationController pushViewController:mvc animated:YES];
}

- (void) enterMapSpot {
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < [arraySpot count]; i++) {
        SpotEntity *entity = [arraySpot objectAtIndex:i];
        [array addObject:entity];
    }
    
    for (int i = 0; i < [arrayBusiness count]; i++) {
        SpotEntity *entity = [arrayBusiness objectAtIndex:i];
        [array addObject:entity];
    }
    
    for (int i = 0; i < [arrayToilet count]; i++) {
        SpotEntity *entity = [arrayToilet objectAtIndex:i];
        [array addObject:entity];
    }
    
    for (int i = 0; i < [arrayHospital count]; i++) {
        SpotEntity *entity = [arrayHospital objectAtIndex:i];
        [array addObject:entity];
    }
    
    for (int i = 0; i < [arrayEnter count]; i++) {
        SpotEntity *entity = [arrayEnter objectAtIndex:i];
        [array addObject:entity];
    }
    
    for (int i = 0; i < [arrayRest count]; i++) {
        SpotEntity *entity = [arrayRest objectAtIndex:i];
        [array addObject:entity];
    }
    
    for (int k = 0; k < [arrayBusinessTogether count]; k++) {
        for (int i = 0; i < [[arrayBusinessTogether objectAtIndex:k] count]; i++) {
            SpotEntity *entity = [[arrayBusinessTogether objectAtIndex:k] objectAtIndex:i];
            [array addObject:entity];
        }
    }
    
    for (int k = 0; k < [arrayTogether count]; k++) {
        for (int i = 0; i < [[arrayTogether objectAtIndex:k] count]; i++) {
            SpotEntity *entity = [[arrayTogether objectAtIndex:k] objectAtIndex:i];
            [array addObject:entity];
        }
    }
  
    if ([parkEntity.use_baidumap isEqualToString:@"0"] == YES) {
        MapImageViewController *vc = [[MapImageViewController alloc] init];
        vc.parkEntity = parkEntity;
        vc.mutableArray = array;
        vc.mutableArrayRoad = arrayRoadLine;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        MapBaiduViewController *vc = [[MapBaiduViewController alloc] init];
        vc.parkEntity = parkEntity;
        vc.mutableArray = array;
        vc.mutableArrayMusic = arraySpot;
        vc.mutableArrayRoad = arrayRoadLine;
        
        //                vc.mutableArraySellTicket= arraySellTicket;
        //                vc.mutableArrayRest = arrayRest;
        //                vc.mutableArrayParkCar = arrayParkCar;
        //                vc.mutableArrayHospital = arrayHospital;
        //                vc.mutableArrayEnter = arrayEnter;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void) enterSpotList {
    SpotViewController *vc = [[SpotViewController alloc] init];
    vc.parkEntity = parkEntity;
    vc.mutableArraySpot = arraySpot;
    [self.navigationController pushViewController:vc animated:YES];
}





@end
